package com.atguigu.juc.study.chapter03.cf.use;

import java.util.concurrent.*;

/**
 * @author : leimingchao
 * @date Date : 2022年06月11日 18:05
 */
public class CompletableFutureUseDemo3 {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        ExecutorService threadPool = Executors.newFixedThreadPool(3);
        try {

            CompletableFuture.supplyAsync(() -> {
                System.out.println(Thread.currentThread().getName() + "-----come in");
                int result = ThreadLocalRandom.current().nextInt(10);
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                System.out.println("-----1秒钟后出结果：" + result);

                if (result > 5) {
                    int i = 10 / 0;
                }
                return result;

            }, threadPool).whenComplete((v, e) -> {
                if (e == null) {
                    System.out.println("----计算完成，更新系统的值：" + v);
                }
            }).exceptionally(e -> {
                e.printStackTrace();
                System.out.println("异常情况：" + e.getCause() + "\t" + e.getMessage());
                return null;
            });

            System.out.println(Thread.currentThread().getName() + "线程先去忙其他任务");

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            threadPool.shutdown();
        }

    }
}
